package com.jack.leetcode.eachProblem08;

public class 二叉树展开为链表 {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    private static TreeNode result = new TreeNode(-1);
    private static TreeNode tmp = result;

    public static void flatten(TreeNode root) {
        if (root == null) {
            return;
        }
        dfs(root);
        root.left = null;
        root.right = result.right.right;
    }

    private static void dfs(TreeNode root) {
        if (root == null) {
            return;
        }
        tmp.right = new TreeNode(root.val);
        tmp = tmp.right;
        dfs(root.left);
        dfs(root.right);

    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.left.left = new TreeNode(3);
        root.left.right = new TreeNode(4);
        root.right = new TreeNode(5);
        root.right.right = new TreeNode(6);
        flatten(root);

    }
}
